import {del, get, set} from '@/api/persistent'
import { DATA_SOURCE_PREFIX } from '@/consts/Consts'
import * as DataSourceService from '@/api/service/dataSourceService'

let logList = {}

export function init(name) {
  logList = persistentGet(name)
  if (logList == null && name !== '' && name != null) {
    logList = {
      name: name,
      index: 0,
      data: []
    }
    DataSourceService.addDataSource(name)
    persistentSet(logList)
  }
  return logList
}

export function getLogList() {
  return logList
}

export function addLogList(_logList) {
  logList.data.push(..._logList)
  correctIndex()
  persistentSet(logList)
}

export function addLog(log) {
  if (log.count > logList.index){
    logList.index = log.count
  }
  logList.data.push(log)
  persistentSet(logList)
}

export function deleteLog(log) {
  const index = logList.data.indexOf(log)
  logList.data.splice(index, 1)

  correctIndex()
  persistentSet(logList)
}

export function updateLog(index, log) {
  logList.data.splice(index, 1, JSON.parse(JSON.stringify(log)))
  correctIndex()
  persistentSet(logList)
}

export function sort(){
  logList.data.sort((a, b) => {
    return a.count > b.count ? 1:-1
  })
  persistentSet(logList)
}

// @TODO 持久化逻辑重复 待改进
export function correctIndex(){
  logList.index = 0
  logList.data.forEach(log => {
    if (log.count > logList.index){
      logList.index = log.count
    }
  })
  persistentSet(logList)
}

export function deleteLogList(name) {
  init()
  persistentDel(name)
}

function persistentSet(logList) {
  set(DATA_SOURCE_PREFIX + logList.name, logList)
}

function persistentGet(name) {
  return get(DATA_SOURCE_PREFIX + name)
}

function persistentDel(name) {
  return del(DATA_SOURCE_PREFIX + name)
}
